<?php

namespace App\Modules\Admin\Http\Middleware;

use App\Traits\Json;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\URL;

class AdminLog
{
    use Json;

    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle(Request $request, Closure $next)
    {
        $guard = 'admin';

        $method = strtoupper($request->getMethod());

        if ($method != 'GET'){
            $ip_agent = get_client_info();

            $log_data = [
                'request_data' => json_encode($request->all()),
                'admin_id'     => !empty(auth($guard)->user()) ? auth($guard)->user()->admin_id : 0,
                'created_ip'   => $ip_agent['ip'] ?? get_ip(),
                'browser_type' => $ip_agent['agent'] ?? $_SERVER['HTTP_USER_AGENT'],
                'created_time' => time(),
                'log_action'   => request()->route()->getActionName(),
                'log_method'   => $method,
                'log_duration' => microtime(true) - LARAVEL_START,
                'request_url'     => URL::full() ?? get_this_url(),
                // 默认值
                'log_status'   => 0,
            ];

            $log_status = 0;
            try{
                $response = $next($request);

                // 获取返回data内容，偶尔会遇到 getData 方法不存在
                if (method_exists($response, 'getData')){
                    $response_body_content = $response->getData() ?? [];
                    // 根据接口响应，存储返回状态与文本提示语
                    $log_status = $response_body_content->status == 1 ? 1 : 0;
                    $log_description = $response_body_content->msg;
                }else{
                    $log_description = 'Method Illuminate\Http\Response::getData does not exist.';
                }

            }catch(\Exception $e){
                $log_description = $e->getMessage();
                $response = $this->errorJson($log_description);
            }

            // 同步更新响应状态与文本，在`handler`层可能会被异常终止
            $log_data['log_duration'] = microtime(true) - LARAVEL_START;
            // 根据接口响应，存储返回状态与文本提示语
            $log_data['log_status'] = $log_status;
            $log_data['description'] = $log_description;
            \App\Modules\Admin\Entities\Log\AdminLog::getInstance()->create($log_data);

            return $response;
        }

        return $next($request);
    }
}
